#include "XVideoUI.h"
#include "ui_XVideoUI.h"
#include <QFileDialog>
#include <string>
#include <QMessageBox>
#include <xvideothread.h>
#include <xaudio.h>
#include <xfilter.h>

#include <QDebug>
using namespace std;

static bool pressSlider = false;
static bool isColor = true;
static bool isMark = false;
static bool isBlend = false;

static bool isExport = false;
static bool isMerge = false;

XVideoUI::XVideoUI(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::XVideoUIClass)
{
    ui->setupUi(this);
    setWindowFlags(Qt::FramelessWindowHint);

    //信号槽不支持mat，要注册一下
    qRegisterMetaType<cv::Mat>("cv::Mat");
    connect(XVideoThread::Get(),SIGNAL(ViewImage1(cv::Mat)),ui->src1Video,SLOT(setImage(cv::Mat)));
    connect(XVideoThread::Get(),SIGNAL(ViewImage2(cv::Mat)),ui->src2,SLOT(setImage(cv::Mat)));
    connect(XVideoThread::Get(),SIGNAL(ViewDes(cv::Mat)),ui->des,SLOT(setImage(cv::Mat)));

    //导出视频结束
    connect(XVideoThread::Get(),SIGNAL(SaveEnd()),this,SLOT(ExportEnd()));


    on_pauseButton_clicked();

    startTimer(40);
}

void XVideoUI::timerEvent(QTimerEvent *event)
{
    // int currentID = event->timerId();
    // if(currentID ==timerID01)
    // {
    //     // info.clear;
    //     killTimer(timerID01);
    //     timerID01 =0;
    // }
    if(pressSlider)
    {
        return;
    }
    double pos = XVideoThread::Get()->GetPos();
    // ui->playSlider2->setValue(pos*1000);//进度条
    ui->playSlider->setValue(pos*1000);//滑动条
}

XVideoUI::~XVideoUI()
{
    delete ui;
}

void XVideoUI::on_closeButton_clicked()
{
    close();
}


void XVideoUI::on_openButton_clicked()
{
    on_playButton_clicked();
    QString name = QFileDialog::getOpenFileName(this,QString::fromLocal8Bit("请选择视频文件"));
    if(name.isEmpty())
        return;
    string file = name.toLocal8Bit().data();

    if(!XVideoThread::Get()->Open(file)){
        QMessageBox::information(this,"error",name +"打开失败");
        return;
    }


}


void XVideoUI::on_playSlider_sliderPressed()
{
    pressSlider =true;

}


void XVideoUI::on_playSlider_sliderReleased()
{

     pressSlider =false;
}


void XVideoUI::on_playSlider_sliderMoved(int position)
{

    XVideoThread::Get()->Seek((double)position/1000.);
}

void XVideoUI::on_left_sliderMoved(int position)
{
    XVideoThread::Get()->SetBegin((double)position/1000.);
    on_playSlider_sliderMoved(position);

}


void XVideoUI::on_right_sliderMoved(int position)
{
    XVideoThread::Get()->SetEnd((double)position/1000.);

}


void XVideoUI::on_setButton_clicked()
{
    XFilter::Get()->Clear();
    isColor = true;

    //视频图像的裁剪
    bool isClip = false;
    int cx = ui->cx->value();
    int cy = ui->cy->value();
    int cw = ui->cw->value();
    int ch = ui->ch->value();

    if(cx +cy +cw +ch >0.0001)
    {
        isClip =true;
        XFilter::Get()->Add(XTask{XTASK_CLIP,{cx,cy,cw,ch}});

        double w = XVideoThread::Get()->width;
        double h = XVideoThread::Get()->height;
        XFilter::Get()->Add(XTask{XTASK_RISIZE,{w,h}});

    }



    //图像金字塔
    bool isPy = false;
    int down = ui->pydown->value();
    int up = ui->pyup->value();
    if(down>0)
    {
        isPy = true;
        XFilter::Get()->Add(XTask{XTASK_PYDOWN,{(double)down}});

        int w = XVideoThread::Get()->width;
        int h = XVideoThread::Get()->height;
        for(int i=0;i<down;i++)
        {

            w =w/2;
            h = h/2;
        }
        ui->width->setValue(w);
        ui->height->setValue(h);

    }
    if( up >0)
    {
        XFilter::Get()->Add(XTask{XTASK_PYUP,{(double)up}});
        int w = XVideoThread::Get()->width;
        int h = XVideoThread::Get()->height;
        for(int i=0;i<down;i++)
        {

            w =w * 2;
            h =h * 2;
        }
        ui->width->setValue(w);
        ui->height->setValue(h);



    }

    //调整视频的尺寸
    if(!isMerge && !isClip &&!isPy && ui->width->value()>0 && ui->height->value()>0)
    {
        XFilter::Get()->Add(XTask{XTASK_RISIZE,{(double)ui->width->value(),ui->height->value()}});

    }

    //对比度和亮度设置
    if((ui->bright->value()>0) || ui->contrast->value()>1)
    {
            XFilter::Get()->Add(XTask{XTASK_GAIN,
                                  {(double)ui->bright->value(),ui->contrast->value()}
        });
    }
    //灰度图
    if(ui->color->currentIndex() ==1)
    {
        XFilter::Get()->Add(XTask{XTASK_GRAY});
        isColor = false;
    }



    //图像旋转ui->rotate->currentIndex()
    switch(ui->rotate->currentIndex()){
    case 1:
        XFilter::Get()->Add(XTask{XTASK_ROTATE90});
        break;
    case 2:
        XFilter::Get()->Add(XTask{XTASK_ROTATE180});
        break;
    case 3:
        XFilter::Get()->Add(XTask{XTASK_ROTATE270});
        break;
    default:
        break;

    };
    //图像镜像
    switch(ui->flip->currentIndex()){
    case 1:
        XFilter::Get()->Add(XTask{XTASK_FLIPX});
        break;
    case 2:
        XFilter::Get()->Add(XTask{XTASK_FLIPY});
        break;
    case 3:
        XFilter::Get()->Add(XTask{XTASK_FLIPXY});
        break;
    default:
        break;
    };

    //设置水印
    if(isMark)
    {
        int x = ui->mx->value();
        int y = ui->my->value();
        int a = ui->ma->value();
        XFilter::Get()->Add(XTask{XTASK_MARK,{x,y,a}});

    }

    //视频融合
    if(isBlend)
    {
        double a = ui->ba->value();
        XFilter::Get()->Add(XTask{XTASK_BLEND,{a}});

    }

    //视频合并
    if(isMerge)
    {
        double h1 = XVideoThread::Get()->height;
        // double h2 = XVideoThread::Get()->height2;
        int w = XVideoThread::Get()->width2;

        XFilter::Get()->Add(XTask{XTASK_MERGE});
        ui->width->setValue(XVideoThread::Get()->width +w);
        ui->height->setValue(h1);
    }
}

void XVideoUI::on_exportButton_clicked()
{

    if(isExport)
    {
        XVideoThread::Get()->StopSave();
        isExport = false;
        ui->exportButton->setText("导出");
        return;
    }

    QString name = QFileDialog::getSaveFileName(this,"save","out1.avi");

    if(name.isEmpty()) return;

    std::string filename = name.toLocal8Bit().data();
    int w = ui->width->value();
    int h = ui->height->value();
    if(XVideoThread::Get()->StartSave(filename,w,h,isColor))
    {
        isExport = true;
        ui->exportButton->setText("停止导出");
    }

}


void XVideoUI::on_playButton_clicked()
{

    ui->pauseButton->show();
    ui->pauseButton->setGeometry(ui->playButton->geometry());
    XVideoThread::Get()->play();
    ui->playButton->hide();
}


void XVideoUI::on_pauseButton_clicked()
{
    ui->playButton->show();
    XVideoThread::Get()->stop();
    ui->pauseButton->hide();
}

//水印
void XVideoUI::on_mark_clicked()
{
    isMark = false;
    isBlend = false;
    isMerge = false;
    QString pic = QFileDialog::getOpenFileName(this,"select image:");

    if(pic.isEmpty())
    {
        return;
    }

    std::string file = pic.toLocal8Bit().data();
    Mat mark = imread(file);
    if(mark.empty()) return;

    XVideoThread::Get()->SetMark(mark);
    isMark = true;

}

//融合
void XVideoUI::on_blendButton_clicked()
{
    isMark = false;
    isBlend = false;
    isMerge = false;

    QString pic = QFileDialog::getOpenFileName(this,"select video:");

    if(pic.isEmpty())
    {
        return;
    }

    std::string file = pic.toLocal8Bit().data();

    isBlend = XVideoThread::Get()->Open2(file);

}
//导出结束
void XVideoUI::ExportEnd()
{
    isExport = false;
    ui->exportButton->setText("导出");

    string src = XVideoThread::Get()->srcFile;
    string des = XVideoThread::Get()->desFile;
    //处理音频
    int ss = 0;
    int t = 0;

    ss =XVideoThread::Get()->totalMs *  ((double)ui->left->value()/1000.);

    int tmp = XVideoThread::Get()->totalMs *  ((double)ui->right->value()/1000.);

    t =tmp -ss;

    string tem = des +".avi";
    QFile::remove(tem.c_str());
    QFile::rename(des.c_str(),tem.c_str());


    XAudio::Get()->ExportA(src,src+ ".mp3",ss ,t);
    XAudio::Get()->Merge(tem,src + ".mp3",des);
}

//合并
void XVideoUI::on_mergeButton_clicked()
{
    isMark = false;
    isBlend = false;
    isMerge = false;

    QString pic = QFileDialog::getOpenFileName(this,"select video:");

    if(pic.isEmpty())
    {
        return;
    }

    std::string file = pic.toLocal8Bit().data();

    isMerge = XVideoThread::Get()->Open2(file);

}



